package com.zz.bid.util;

import com.zz.bid.exception.CacheNotExistException;
import com.zz.bid.exception.base.BidException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

@Component
public class EhcacheMapper {

    @Autowired
    private CacheManager cacheManager;

    private static String CACHE_KEY = "bid-cache";

    @SuppressWarnings({"unchecked"})
    public <T> T get(String key) {
        Cache cache = cacheManager.getCache(CACHE_KEY);
        if (null != cache) {
            Cache.ValueWrapper valueWrapper = cache.get(key);
            if (null != valueWrapper) {
                return (T) valueWrapper.get();
            }
        }
        return null;
    }

    public synchronized void set(String key, Object value) throws BidException {
        Cache cache = cacheManager.getCache(CACHE_KEY);
        if (null == cache) {
            throw new CacheNotExistException();
        }
        cache.put(key, value);
    }

    public void remove(String key) throws BidException {
        Cache cache = cacheManager.getCache("misCache");
        if (null == cache) {
            throw new CacheNotExistException();
        }
        cache.evict(key);
    }
}
